package com.hangxintong.common;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

//import sun.font.FontDesignMetrics;

public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 给图片+图片水印
     *
     * @param url       --url 地址
     * @param pressImg  -- 水印图片
     * @param targetImg -- 目标文件
     * @param location  水印位置：left-top：左上角，right-top：右上角，left-bottom：左下角，right-bottom：右下角
     * @param degree    水印旋转角度
     */

    public static void pressImage(String url,
                                  String presstxt,
                                  String pressImg,
                                  String targetImg,
                                  String location,
                                  Integer degree,
                                  int addressX,
                                  int addressY) {
        try {
            // 目标文件
            File _file = toFile(url, new File(targetImg));
            Image src = ImageIO.read(_file);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            // 水印文件
            File _filebiao = new File(pressImg);
            Image src_biao = ImageIO.read(_filebiao);
            int width_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            // 水印坐标
            int x = 0, y = 0;
            if (StringUtils.equals(location, "left-top")) {
                x += 30;
                y += 30;
            } else if (StringUtils.equals(location, "right-top")) {
                x = width - width_biao - 30;
                y += 30;
            } else if (StringUtils.equals(location, "left-bottom")) {
                y = height - height_biao - 30;
                x += 30;
            } else if (StringUtils.equals(location, "right-bottom")) {
                x = width - width_biao - 30;
                y = height - height_biao - 30;
            } else if (StringUtils.equals(location, "center")) {
                x = (width - width_biao) / 2;
                y = (height - height_biao) / 2;
            } else {
//                x = (width - width_biao) / 2;
//                y = (height - height_biao) / 2;
                x += addressX;
                y += addressY;
            }
            if (null != degree) {
                // 设置水印旋转
                g.rotate(Math.toRadians(degree), x, y);
            }
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g.drawImage(src_biao, x, y, width_biao, height_biao, null);

            //


            String[] strArr = presstxt.split("\n");
            int image_width = 400; // 每张图片的高度
            int image_height = 700; // 每张图片的高度
            int line_height = 30; // 每行或者每个文字的高度
            int every_line = image_height / line_height; // 每张图片有多少行文字
            // Image fontImg = ImageUtils.createTextImage(strArr, new Font("宋体", Font.PLAIN, 22), image_width, image_height, every_line, line_height);
            // g.drawImage(fontImg, 10, 10, null);
            // 水印文件结束
            g.dispose();
            //直接修改源文件
            //FileOutputStream out = new FileOutputStream(targetImg);
            // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(image);
            //out.flush();
            //out.close();
            String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);

            ImageIO.write(image, formatName, new FileOutputStream(targetImg));


            //生成新的文件
            //File sf = new File("D:/imgout/" + "test" + "." + "jpg");
            //ImageIO.write(image, "jpg", sf); // 保存图片
        } catch (Exception e) {
            log.error("设置图片水印异常：{}", e.getMessage(), e);
        }
    }

    /**
     * 给图片加文字水印
     *
     * @param url       图片的网络地址
     * @param pressText s水印文字
     * @param targetImg 目标文件
     * @param fontName  字体名称
     * @param fontStyle 字体风格
     * @param fontSize  字体大小
     * @param location  字体位置:left-top：左上角，right-top：右上角，left-bottom：左下角，right-bottom：右下角
     */

    public static void pressText(String url,
                                 String pressText,
                                 String targetImg,
                                 String fontName,
                                 int fontStyle,
                                 int fontSize, String location,
                                 Color color,
                                 int addressX,
                                 int addressY,
                                 Image fontImg) {
        try {
            int textWidth = getFontWidth(fontName, fontStyle, fontSize, pressText);
            File newfile = toFile(url, new File(targetImg));
            Image src = ImageIO.read(newfile);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g.drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    0.45f));
            int x = 0, y = 0;
            if (StringUtils.equals(location, "left-top")) {
                x = 30;
                y = 30;
            } else if (StringUtils.equals(location, "right-top")) {
                x = width - textWidth - 30;
                y = 30;
            } else if (StringUtils.equals(location, "left-bottom")) {
                x += 30;
                y = height - 30;
            } else if (StringUtils.equals(location, "right-bottom")) {
                x = width - textWidth - 30;
                y = height - 30;
            } else {
//                x = (width - textWidth) / 2;
//                y = (height) / 2;
                x += addressX;
                y += addressY;
            }
            g.drawString(pressText, x, y);
            g.drawString(String.valueOf(System.currentTimeMillis()), x, y + fontSize + 10);
            g.dispose();
            //原代码
            //FileOutputStream out = new FileOutputStream(targetImg);
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(image);
            //out.flush();
            //out.close();
            //修改如下
            String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);
            ImageIO.write(image, formatName, new FileOutputStream(targetImg));
        } catch (IOException e) {
            log.error("设置文字水印异常：{}", e.getMessage(), e);
        }


    }


    /**
     * 文件保存
     *
     * @param link 图片链接
     * @param file 存入的文件地址
     * @return 下载的文件
     */
    public static File toFile(String link, File file) {
        try {

            URL url = new URL(link);
            URLConnection uri = url.openConnection();
            //获取数据流
            InputStream ins = uri.getInputStream();
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return file;
        } catch (Exception e) {
            log.error("文件保存异常：{}", e.getMessage(), e);
            return null;
        }

    }

    /**
     * 计算文本占用的width
     *
     * @param fontName  字体名称
     * @param fontStyle 字体风格
     * @param fontSize  字体大小
     * @param pressText 输入文本
     * @return 文字所占用的宽带
     */
    public static int getFontWidth(String fontName, int fontStyle, int fontSize, String pressText) {
        Font f = new Font(fontName, fontStyle, fontSize);

        JLabel label = new JLabel(pressText);
        FontMetrics metrics = label.getFontMetrics(f);
        //文字水印的宽度
        int width = metrics.stringWidth(label.getText());
        return width;
    }

    public static int myGetFontWidth(Font f, String pressText) {
        JLabel label = new JLabel(pressText);
        FontMetrics metrics = label.getFontMetrics(f);
        //文字水印的宽度
        int width = metrics.stringWidth(label.getText());
        return width;
    }

    public static void main(String[] args) {
//        pressImage("D:/projects/image/4771117140_1239574879.jpg", "D:/projects/image/certificate.png", "D:/projects/image/base.jpg", "right-bottom", null,0,0);//
//        pressImage("D:/imgin/20181017110944.png", "D:/imgout/1.png", "right-top", null);
//        pressImage("D:/imgin/20181017110944.png", "D:/imgout/1.png", "center", null);
//        pressImage("D:/imgin/20181017110944.png", "D:/imgout/1.png", "left-bottom", null);
//        pressImage("D:/imgin/20181017110944.png", "D:/imgout/1.png", "right-bottom", null);
      // pressText("http://192.168.0.222:9092/resources/20200428/05588a12-89fc-4c0b-ab82-1e1f3019d023.png", "miraclad发送到发烧是打发打发esgrocery", "D:/projects/image/base.jpg", "黑体", Font.BOLD + Font.ITALIC, 30, "",Color.GRAY,50,50);
        int fontWidth = getFontWidth("黑体", Font.BOLD + Font.ITALIC, 30, "miraclesgrocery");
        System.out.println(fontWidth);
        System.out.println(Font.BOLD + Font.ITALIC);
        System.out.println(Color.RED);
        System.out.println(Color.WHITE);
        System.out.println(Color.GRAY);
  }

    /**
     * 根据str,font的样式等生成图片
     * https://blog.csdn.net/sinat_28505133/article/details/54669111
     *
     * @param strArr
     * @param font
     * @param width
     * @param image_height
     * @throws Exception
     */
//    private static Image createTextImage(String[] strArr, Font font,
//                                         int width, int image_height,
//                                         int every_line, int line_height) throws Exception {
//
//        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
//        int stringWidth = fm.charWidth('字');// 标点符号也算一个字
//        int line_string_num = width % stringWidth == 0 ? (width / stringWidth) : (width / stringWidth) + 1;
//        System.out.println("每行=" + line_string_num);
//        List<String> listStr = new ArrayList<>();
//        List<String> newList = new ArrayList<>();
//        for (int h = 0; h < strArr.length; h++) {
//            listStr.add(strArr[h]);
//        }
//        for (int j = 0; j < listStr.size(); j++) {
//            if (listStr.get(j).length() > line_string_num) {
//                newList.add(listStr.get(j).substring(0, line_string_num));
//                listStr.add(j + 1, listStr.get(j).substring(line_string_num));
//                listStr.set(j, listStr.get(j).substring(0, line_string_num));
//            } else {
//                newList.add(listStr.get(j));
//            }
//        }
//
//        int a = newList.size();
//        int b = every_line;
//        int imgNum = a % b == 0 ? (a / b) : (a / b) + 1;
//
//        for (int m = 0; m < imgNum; m++) {
//            //String filePath = "C:\\Users\\diyan\\Pictures\\d" + m + ".jpg";
//            //File outFile = new File(filePath);
//            // 创建图片
//            BufferedImage image = new BufferedImage(width, image_height,
//                    BufferedImage.TYPE_INT_BGR);
//            Graphics g = image.getGraphics();
//            g.setClip(0, 0, width, image_height);
//            g.setColor(Color.white); // 背景色白色
//            g.fillRect(0, 0, width, image_height);
//            g.setColor(Color.black);//  字体颜色黑色
//            g.setFont(font);// 设置画笔字体
//            // 每张多少行，当到最后一张时判断是否填充满
//            for (int i = 0; i < every_line; i++) {
//                int index = i + m * every_line;
//                if (newList.size() - 1 >= index) {
//                    System.out.println("每行实际=" + newList.get(index).length());
//                    g.drawString(newList.get(index), 0, line_height * (i + 1));
//                }
//            }
//            g.dispose();
//            return image;
//        }
//
//        return null;
//    }
//    public static void previewExamCert(PreviewCertDTO previewCertDTO) {
//        try {
//            String targetImg = "D:/projects/image/target22.jpg";
//            File newfile = toFile(previewCertDTO.getCustomCertPath(), new File(targetImg));
//
//            Image src = ImageIO.read(newfile);
//            int width = src.getWidth(null);
//            int height = src.getHeight(null);
//            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//            Graphics2D g = image.createGraphics();
//            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//            g.drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//            int x = 0, y = 0;
//
//            //证书名称
//            Font titleFont = new Font("黑体", Font.BOLD + Font.ITALIC, 40);
//
//            int titleWidth = myGetFontWidth(titleFont, previewCertDTO.getTitle());
//            g.setColor(Color.BLACK);
//            g.setFont(titleFont);
//            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.45f));
//
//            x = (width - titleWidth) / 2;
//            y = (height) / 8;
//            g.drawString(previewCertDTO.getTitle(), x, y);
//
//            //获奖人
//
//            Font userFont = new Font("黑体", Font.BOLD + Font.ITALIC, 30);
////            int textWidth = myGetFontWidth(userFont, previewCertDTO.getTitle());
//            g.setColor(Color.BLACK);
//            g.setFont(userFont);
//            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.45f));
//
//            x = width / 9;
//            y = height / 6;
//            g.drawString(previewCertDTO.getUserName(), x, y);
//
//            //文字说明
//            String[] strArr = previewCertDTO.getCertExplain().split("\n");
//            int image_width = 700; // 每张图片的高度
//            int image_height = 400; // 每张图片的高度
//            int line_height = 30; // 每行或者每个文字的高度
//            int every_line = image_height / line_height; // 每张图片有多少行文字
//            // Image fontImg = ImageUtils.createTextImage(strArr, new Font("黑体", Font.PLAIN, 22), image_width, image_height, every_line, line_height);
//            x = (width - image_width) / 2;
//            y = (height - image_height) / 2;
//            // g.drawImage(fontImg, x, y, null);
//
//
//            //公章
//            File _filebiao = new File("D:/projects/image/certificate_honor.png");
//            Image src_biao = ImageIO.read(_filebiao);
//            int width_biao = src_biao.getWidth(null);
//            int height_biao = src_biao.getHeight(null);
//            x = width - 200;
//            y = height - 200;
//            g.drawImage(src_biao, x, y, width_biao, height_biao, null);
//
//
//            //时间日期
//            Font timeFont = new Font("黑体", Font.ITALIC, 12);
////            int timeWidth = myGetFontWidth(timeFont, "年&nbsp;&nbsp;&nbsp;月&nbsp;&nbsp;&nbsp;&nbsp;日");
//            g.setColor(Color.BLACK);
//            g.setFont(timeFont);
//            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.45f));
//
//            x = width - 200;
//            y = height - 100;
//            g.drawString("年  月  日", x, y);
//
//            g.dispose();
//            String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);
//            ImageIO.write(image, formatName, new FileOutputStream(targetImg));
//
//        } catch (Exception e) {
//            throw new GlobalException(StatusCode.ERROR, "异常信息");
//        }
//
//    }

}

